Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};       
//this variable represents the total number of popups can be displayed according to the viewport width
var total_popups = 0;

//arrays of popups ids
var popups = [];

//this is used to close a popup
function close_popup(id) {
    for(var iii = 0; iii < popups.length; iii++) {
        if(id == popups[iii]) {
            Array.remove(popups, iii);
            document.getElementById('chat_box_' + id).style.display = "none";
            calculate_popups();
            return;
        }
    }   
}

//displays the popups. Displays based on the maximum number of popups that can be displayed on the current viewport width
function display_popups(){
    var right = 260;
    var iii = 0;
    for(iii; iii < total_popups; iii++) {
        if(popups[iii] != undefined) {
            var element = document.getElementById('chat_box_' +popups[iii]);
            element.style.right = right + "px";
            right = right + 320;
            element.style.display = "block";
        }
    }
        
    for(var jjj = iii; jjj < popups.length; jjj++) {
        var element = document.getElementById('chat_box_' +popups[jjj]);
        console.log(element);
        element.style.display = "none";
    }
}
    
//creates markup for a new popup. Adds the id to popups array.
function register_popup(id, name) {
    
    for(var iii = 0; iii < popups.length; iii++) {   
        //already registered. Bring it to front.
        if(id == popups[iii]) {
            Array.remove(popups, iii);
            
            popups.unshift(id);
                
            calculate_popups();
                
            return;
        }
    }               
        
        var template = $('#chatPopTpl').html();
        var data = {id:id,name:name};
        var element = Mustache.to_html(template,data);
        
        document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;  

        popups.unshift(id);
                
        calculate_popups();               
        
        $('#message_container_'+id).html('<center><img src="' + URL + 'img/loading.gif"/></center>');
        listMessages(id).done(function(result){
        $('#message_container_'+id).html('');    
            $(result.data).each(function(i,val){
                addMessage(id,val.cr.message,val.profile_pic,val.fname+' '+val.lname,val.cr.date_created);
            });
        });
}
    
//calculate the total number of popups suitable and then populate the toatal_popups variable.
function calculate_popups() {
    var width = window.innerWidth;
        if(width < 540) {
            total_popups = 0;
        }
        else {
            width = width - 200;
            //320 is width of a single popup box
            total_popups = parseInt(width/320);
        }
        
        display_popups();        
 }
            
    //recalculate when window is loaded and also when window is resized.
    window.addEventListener("resize", calculate_popups);
    
    $(window).on('load',function(){

        calculate_popups();
    });

    
    // INITIALIZE variables
    var $chatContainer = $('#chat_container');
    var SOCKET_ID = null;

    function listMessages(recipient_id)
    {   
        var params = {};
        params.recipient_id = recipient_id;

        return $.ajax({
            url: URL + 'messages/list',
            type: 'get',
            data: params,
            dataType: 'json'
        });
    }

    function addMember(data)
    {
        //if(data.id != SS_USER_ID){
            var template = $('#onlineTpl').html();
            var html = Mustache.to_html(template,data);
            $chatContainer.append(html);
            updateTotalCount();
       // }
    }

    function removeMember(data)
    {
        $('#chat_id_' + data.id).fadeOut('slow',function(){
            $(this).remove();
            updateTotalCount();
        });        
    }

    function updateTotalCount()
    {
        $('#chat_online').text($('.chat_member').length);
    }

$(function(){
    $(document).ready(function(){
        pusher = new Pusher(PUSHER_APP_KEY, { authEndpoint: 'users/presence' }); //APP KEY
        
        nettuts_channel = pusher.subscribe('presence-my-channel'); //join the presence-nettuts channel

        pusher.connection.bind('connected', function(){ //bind a function after we've connected to Pusher
        SOCKET_ID = pusher.connection.socket_id;
            nettuts_channel.bind('pusher:subscription_succeeded', function(members) {
                members.each(function(member){
                    if(member.info.data.id != SS_USER_ID){
                        addMember(member.info.data);
                    }
                });   
                $('#chatLoading').hide();  
            });
            nettuts_channel.bind('pusher:member_added', function(member) {
                addMember(member.info.data);
            });

            nettuts_channel.bind('pusher:member_removed', function(member){
                removeMember(member.info.data);
            });

        });

        var channel = pusher.subscribe('my-channel');        
        
        channel.bind('message-sent', function(data){
            addMessage(data.sender_id,data.message,data.sender_prof_pic,data.sender_fullname,CURR_DATE);
            jQuery("abbr.timeago").timeago();
        }); 


        $(document).on('click','.closePopUp',function(){
            var id = $(this).attr('data_id');
            close_popup(id);
        });

        $(document).on('keypress','.chatTrigger',function(e){
            if(e.which == 13 && !e.shiftKey){

                 var recipient_id = $(this).attr('data_id');
                 var message = $(this).val();
            
                 addMessage(recipient_id,message,SS_PROF_PIC,SS_FULLNAME,CURR_DATE);

                 sendMessage(recipient_id,message).done(function(result){
                    
                 });

                 $(this).val('');
                 return false;
                 //$(this).blur();
                 //$(this).focus();
            }
        });
    });
});
   

function addMessage(id,message,prof_pic,fullname,date_created){
    var $container = $('#message_container_'+id);
    var data = {
        fullname: fullname,
        message: message,
        recipient_prof_pic: prof_pic,
        date_created:date_created
    };
    
    var template = $('#youTpl').html();
    var html = Mustache.to_html(template,data);
    $container.append(html);

    $container.scrollTop($container[0].scrollHeight);

    jQuery("abbr.timeago").timeago();
}

function sendMessage(id,message){
    //alert(SOCKET_ID);
    var params = {};
    params.recipient_id = id;
    params.message = message;
    params.socket_id =  SOCKET_ID;
    return $.ajax({
        url: URL + 'messages/send',
        type: 'post',
        data: params,
        dataType: 'json'
    });
}